package com.baomidou.ant.controller;

import com.baomidou.ant.common.Result;
import com.baomidou.ant.entity.CpkInfo;
import com.baomidou.ant.entity.SysUser;
import com.baomidou.ant.entity.WorkOrder;
import com.baomidou.ant.service.ICpkInfoService;
import com.baomidou.ant.service.ISysUserService;
import com.baomidou.ant.service.IWorkOrderService;
import com.baomidou.ant.utils.MyMathUtils;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/cpk-info")
public class CpkInfoController {
    @Autowired
    ICpkInfoService cpkInfoService;

    //cpk计算接口
    @PostMapping("/cpkCount")
    public Result cpkCount(@RequestBody RequestCpkCountVo vo){
        List<Double> dataList=vo.getDataList();
        double allTotal=0;
        for(Double data:dataList){
            allTotal=allTotal+data;
        }
        //平均数
        double X=allTotal/dataList.size();
        //规格中心值
        double C=(vo.getUsl()+vo.getLsl())/2;
        //规格公差
        double T=vo.getUsl()-vo.getLsl();
        //标准差
        double sd= MyMathUtils.standardDeviaction(dataList);
        //CA，取绝对值
        double ca= Math.abs((X-C)/(T/2));
        //CP
        double cp=T/(6*sd);
        //CPK
        double cpk=cp*(Math.abs(1-ca));
        //值返回
        ResponseCpkResultVo resultVo=new ResponseCpkResultVo();
        //保留3位小数点
        DecimalFormat df = new DecimalFormat("#0.000");
        resultVo.setCa(df.format(ca*100)+"%");
        resultVo.setCp(df.format(cp));
        resultVo.setCpk(df.format(cpk));
        return Result.getSuccess().setData(resultVo);
    }

    //结果保存接口
    @PostMapping("/saveResult")
    public Result saveResult(@RequestBody RequestSaveCpkResultVo vo){
        //先校验是否计算过此数据
        if(ObjectUtils.isNotEmpty(cpkInfoService.queryByOrderNum(vo.getOrderNum()))){
            return Result.getFailure().setMsg("该lot已经计算过cpk,请勿重复提交！");
        }
        CpkInfo cpkInfo=new CpkInfo();
        BeanUtils.copyProperties(vo,cpkInfo);
        cpkInfo.setUsl(Double.valueOf(vo.getUsl()));
        cpkInfo.setLsl(Double.valueOf(vo.getLsl()));
        cpkInfo.setSData(MyStringUtil.strToString(vo.getDataList()));
        if(cpkInfoService.save(cpkInfo)){
            return Result.getSuccess().setMsg("结果保存成功!");
        }else
            return Result.getFailure().setMsg("结果保存失败！");
    }

    @PostMapping("/getCpkChart")
    public Result getCpkChart(@RequestBody RequestGetCpkChartVo vo){
        ResponseCpkChartVo responseCpkChartVo=cpkInfoService.getChartData(vo);
        if(ObjectUtils.isEmpty(responseCpkChartVo.getCpkList())&&ObjectUtils.isEmpty(responseCpkChartVo.getOrderNumList())){
            return Result.getFailure().setMsg("当前部门或者当前机台下没有CPK指数记录！");
        }
        return Result.getSuccess().setData(responseCpkChartVo);
    }

    @PostMapping("/getAllCpkChart")
    public Result getAllCpkChart(@RequestBody RequestGetAllCpkChartVo vo){
        ResponseAllCpkChartVo responseAllCpkChartVo=cpkInfoService.getAllChartData(vo);
        if(ObjectUtils.isEmpty(responseAllCpkChartVo.getCpkList())&&ObjectUtils.isEmpty(responseAllCpkChartVo.getNumList())){
            return Result.getFailure().setMsg("当前部门没有CPK指数记录！");
        }
        return Result.getSuccess().setData(responseAllCpkChartVo);
    }

    @Autowired
    ISysUserService userService;

    @PostMapping("/searchCpk")
    public Result searchCpk(@RequestBody RequestSearchCpkVo vo){
        QueryWrapper<CpkInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",vo.getOrderNum());
        SysUser user=userService.queryByLoginName(vo.getLoginName());
        //判断管理员级别
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(ObjectUtils.isNotEmpty(vo.getDeptId())){
                queryWrapper.eq("dept_id",vo.getDeptId());
            }
        } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//只能看自己部门的
            queryWrapper.eq("dept_id",user.getDeptId());
        }
        CpkInfo cpkInfo=cpkInfoService.getOne(queryWrapper);
        if(ObjectUtils.isEmpty(cpkInfo)){
            return Result.getFailure().setMsg("没有查询到CPK记录!");
        }else{
            ResponseSearchCpkVo responseSearchCpkVo=new ResponseSearchCpkVo();
            BeanUtils.copyProperties(cpkInfo,responseSearchCpkVo);
            return Result.getSuccess().setData(responseSearchCpkVo);
        }
    }

    @PostMapping("/listAll")
    public Result listAll(@RequestBody RequestSearchCpkVo vo){
        IPage<ResponseListAllCpkVo> iPage=cpkInfoService.listAllCpk(vo);
        return Result.getSuccess().setData(iPage);
    }

    @PostMapping("/updateCpk")
    public Result updateCpk(@RequestBody RequestUpdateCpkVo vo){
        CpkInfo cpkInfo=cpkInfoService.queryByOrderNum(vo.getOrderNum());
        String[] dataList=vo.getDataList();
        //转化为集合
        List<Double> list=new ArrayList<>();
        double allTotal=0;
        for(int i=0;i<dataList.length;i++){
            allTotal=allTotal+Double.parseDouble(dataList[i]);
            list.add(Double.valueOf(dataList[i]));
        }
        //平均数
        double X=allTotal/dataList.length;
        //规格中心值
        double C=(Double.parseDouble(vo.getUsl())+Double.parseDouble(vo.getLsl()))/2;
        //规格公差
        double T=Double.parseDouble(vo.getUsl())-Double.parseDouble(vo.getLsl());
        //标准差
        double sd= MyMathUtils.standardDeviaction(list);
        //CA，取绝对值
        double ca= Math.abs((X-C)/(T/2));
        //CP
        double cp=T/(6*sd);
        //CPK
        double cpk=cp*(Math.abs(1-ca));
        //保留3位小数点
        DecimalFormat df = new DecimalFormat("#0.000");
        cpkInfo.setCa(Double.valueOf(df.format(ca*100)));
        cpkInfo.setCp(Double.valueOf(df.format(cp)));
        cpkInfo.setCpk(Double.valueOf(df.format(cpk)));
        cpkInfo.setSData(MyStringUtil.strToString(dataList));
        cpkInfo.setLsl(Double.valueOf(vo.getLsl()));
        cpkInfo.setUsl(Double.valueOf(vo.getUsl()));
        if(cpkInfoService.updateById(cpkInfo)){
            return Result.getSuccess().setMsg("修改成功！");
        }else
            return Result.getFailure().setMsg("修改失败!");

    }

    @Autowired
    IWorkOrderService workOrderService;
//    @PostMapping("/insertCpk")
//    public Result insertCpk(@RequestBody RequestDtoVo vo){
//        QueryWrapper<WorkOrder> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("order_dept",vo.getDeptId());
//        List<WorkOrder> orderList=workOrderService.list(queryWrapper);
//        List<String> orderNumList=new ArrayList<>();
//        for(WorkOrder workOrder:orderList){
//            orderNumList.add(workOrder.getOrderNum());
//        }
//        for(int i=0;i<orderNumList.size();i++){
//            CpkInfo cpkInfo=new CpkInfo();
//            double max=2.00;
//            double min=1.33;
//            double cpk=Math.random() * (max - min) + min;
//            DecimalFormat df = new DecimalFormat("#0.000");
//            cpkInfo.setCpk(Double.valueOf(df.format(cpk)));
//            cpkInfo.setOrderNum(orderNumList.get(i));
//            cpkInfo.setDeptId(vo.getDeptId());
//            cpkInfo.setMachineNum("B001");
//            cpkInfoService.save(cpkInfo);
//        }
//        return Result.getSuccess();
//    }

    @PostMapping("/listCpkResult")
    public Result listCpkResult(@RequestBody RequestDtoVo vo){
        CpkInfo cpkInfo=cpkInfoService.queryByOrderNum(vo.getOrderNum());
        ResponseCpkResultVo resultVo=new ResponseCpkResultVo();
        resultVo.setCa(String.valueOf(cpkInfo.getCa()));
        resultVo.setCp(String.valueOf(cpkInfo.getCp()));
        resultVo.setCpk(String.valueOf(cpkInfo.getCpk()));
        return Result.getSuccess().setData(resultVo);
    }

    @GetMapping("/listInfo/{orderNum}")
    public Result listInfo(@PathVariable String orderNum){
        CpkInfo cpkInfo=cpkInfoService.queryByOrderNum(orderNum);
        ResponseListCpkInfoVo vo=new ResponseListCpkInfoVo();
        BeanUtils.copyProperties(cpkInfo,vo);
        if(ObjectUtils.isEmpty(cpkInfo.getSData())){
            vo.setSData(new String[10]);
        }else
            vo.setSData(cpkInfo.getSData().split(";"));
        return Result.getSuccess().setData(vo);
    }



}
